<template>
  <div>
    <!--条件筛选-->
    <TopFilter ref="topFilter" :list="topFilterList" :cols="3" labelWidth="110" @filterChange="changeHandle" @onCollapse="collapseHandle"></TopFilter>

    <FilterTable
      ref="table"
      columnsRef="testindex"
      :columns="columns"
      :fetchapi="fetchApi"
      :params="fetchParams"
      :isExportExcel2="true"
      exportFileName="电池维修信息.xlsx"
      :datakey="'records'"
      :onColumnsChange="columns => (this.columns = columns)"
      :onRowSelectChange="selectData"
    >
      <!-- <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="saveJk()">测试接口</el-button>
      </template> -->
      <template slot="controls">
        <el-button size="small" type="primary" icon="el-icon-plus" @click="openimportPjDialog()">标记完成导入</el-button>
        <el-button size="small" type="primary" @click="doComplete()" :disabled="isOpen">批量标记完成</el-button>
      </template>
    </FilterTable>

    <BaseDialog
      :visible.sync="issearch"
      :title="'经销商查询'"
      destroyOnClose
      :containerStyle="{height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '60px'}"
    >
      <ownerSeacher  @close="dealercloseHandler" />
    </BaseDialog>


    <BaseDialog style="min-height: 80vh;" :visible.sync="visibleImportFlag" width="80vw" title="导入已完成维修单" destroyOnClose
                :containerStyle="{ height: 'calc(100% - 60px)', overflow: 'auto', paddingBottom: '50px' }"
    >
      <ExcelImport
        ref="import"
        template-file-name="电池维修信息导入完成模板.xlsx"
        :importRules="importRules"
        :onBeforeDownloadTemp="onBeforeDownloadTemp"
        :onComplete="importComplete"
        @close="visibleImportFlag = false"
      />
    </BaseDialog>
  </div>
</template>

<script>
import { wcztArr } from './constant';
import { getRepairData, postSave, saveExcel, batchConpleteUpdate } from '@/api/serviceass/batteryService/repair';
import { dictionary } from '@/utils/dictMixin';
import ownerSeacher from '../../../partsmanage/claim/approve/ownerSeacher';
import ExcelImport from '@/components/ExcelImport';
export default {
  name: 'servicessbatteryservicerepairindex',
  mixins: [dictionary],
  components: {
    ownerSeacher,
    ExcelImport
  },
  data() {
    return {
      topFilterList: this.createTopFilterList(),
      columns: this.createTableColumns(),
      fetchParams: { xhrAbort: true },
      fetchApi: getRepairData,
      issearch: false,
      visibleImportFlag: false,
      isOpen: true,
      importRules: [
        {prop: 'roNo', title: '维修工单号',
          rule: [
          { required: true, message: '维修工单号不能为空' },
        ]},
        {prop: 'ownerCode', title: '经销商代码',
          rule: [
            { required: true, message: '经销商代码不能为空' },
          ]},
        {prop: 'handleResult', title: '完成状态',
          rule: [
          // { required: true, message: '完成状态不能为空' },
          {
            validator: (callback, rule, val, row, datas) => {
              if (val !== null && val !== undefined && val !== 'Y' && val !== 'N' && val !== '') {
                callback(new Error('请输入正确完成状态(已完成-Y，未完成-N)'))
              } else {
                callback()
              }
            }
          }
        ]},
      ]
    }
  },
  methods: {
    createTopFilterList() {
      return [
        {
          type: 'INPUT',
          label: 'VIN',
          fieldName: 'vin'
        },
        {
          type: 'INPUT',
          label: '工单号',
          fieldName: 'roNo'
        },
        {
          type: 'INPUT',
          label: '车牌号',
          fieldName: 'license'
        },
        {
          type: 'SELECT',
          label: '工单状态:',
          fieldName: 'roStatus',
          placeholder: '请选择...',
          itemList: this.createDictList('8049')
        },
        {
          type: 'SELECT',
          label: '电池品牌:',
          fieldName: 'cellBrand',
          placeholder: '请选择...',
          itemList: this.createDictList('5014')
        },
        {
          type: 'INPUT',
          label: '车型',
          fieldName: 'model_name'
        },
        {type: 'RANGE_DATE', label: '开单时间', fieldName: 'createdAt1|createdAt2', valueFormat: 'yyyy-MM-dd', placeholder: '请选择'},
        {
          type: 'INPUT',
          label: '经销商名称',
          fieldName: 'dealerCode',
          placeholder: '请选择',
          unitRender: () => {
            return (
              <div>
                <el-button icon="el-icon-search" onClick={() => this.seacherFun()}></el-button>
              </div>
            );
          },
          change:p=>{
            if(!p){
              this.dealerCode=''
            }
          }
        },
        {
          type: 'SELECT',
          label: '完成状态:',
          fieldName: 'handleResult',
          placeholder: '请选择...',
          itemList: wcztArr
        },
      ]
    },
    changeHandle(val) {
      this.isOpen=true;
      val.createdAt2 && (val.createdAt2 = val.createdAt2.split(' ')[0] + ' 23:59:59');
      this.fetchParams = Object.assign({}, val);
    },
    collapseHandle() {
      this.$nextTick(() => {
        this.BaseTable.EXECUTE_RESET_HEIGHT();
      });
    },
    createTableColumns() {
      return [
        {
          title: '序号',
          dataIndex: 'index',
          width: 80,
          sorter: true,
          render: props => {
            return <span>{props.row.index + 1}</span>;
          }
        },
        {
          title: '工单开单时间',
          dataIndex: 'roCreateDate',
          sorter: true,
          dateFormat: 'YYYY-MM-DD HH:mm:ss',
          exportFormat: {
            t: 'd'
          }
        },
        {
          title: '工单号',
          dataIndex: 'roNo',
          sorter: true,
          width: 130
        },
        {
          title: '经销商',
          dataIndex: 'ownerCode2',
          sorter: true,
          width: 160
        },
        {
          title: '经销商代码',
          dataIndex: 'ownerCode',
          sorter: true,
        },
        // {
        //   title: '预约单号',
        //   dataIndex: 'bookingOrderNo',
        //   sorter: true,
        //   width: 130
        // },
        {
          title: '电池品牌',
          dataIndex: 'cellBrand',
          sorter: true,
          dictItems: this.createDictList('5014')
        },
        {
          title: '店端电池维修负责人',
          dataIndex: 'cellRepairName',
          sorter: true,
        },
        {
          title: '店端负责人电话',
          dataIndex: 'cellRepairPhone',
          sorter: true,
        },
        {
          title: '服务顾问',
          dataIndex: 'serviceAdvisor',
          sorter: true,
        },
        {
          title: '车牌号',
          dataIndex: 'license',
          sorter: true,
          width: 160
        },
        {
          title: 'VIN',
          dataIndex: 'vin',
          sorter: true,
          width: 160
        },
        {
          title: '车型',
          dataIndex: 'model_name',
          sorter: true,
        },
        {
          title: '车辆销售日期',
          dataIndex: 'salesDate',
          sorter: true,
          filter: true,
          filterType: 'date-range',
          dateFormat: 'YYYY-MM-DD',
          exportFormat: {
            t: 'd'
          }
        },
        {
          title: '公里数',
          dataIndex: 'inMileage',
          sorter: true,
          filter: true,
          filterType: 'number'
        },
        {
          title: '客户描述',
          dataIndex: 'customerDesc',
          sorter: true,
          width: 160
        },
        {
          title: '完成状态',
          dataIndex: 'handleResult',
          sorter: true,
          dictItems: wcztArr
        },
        // {
        //   title: '工单状态',
        //   dataIndex: 'roStatus',
        //   sorter: true,
        //   dictItems: this.createDictList('8049')
        // },
      ];
    },
    async saveJk() {
      var obj = {}
      obj.id = '37642'
      obj.batteryBrand = '50141002'
      obj.dealerCode = 'R110101'
      let res=await postSave(obj)
      console.info(res)
    },
    seacherFun(){
      this.issearch=true;
    },
    dealercloseHandler(val){
      console.info(val)
      if(val){
        this.topFilterList.find(x=>x.fieldName=='dealerCode').initialValue=val.dealerCode;
        this.fetchParams=Object.assign({
          dealerCode: val.dealerCode
        },this.fetchParams)
        this.dealerCode=val.dealerCode
      }
      this.issearch=false;
    },
    openimportPjDialog() {
      this.visibleImportFlag = true
    },
    async importComplete(datas,callback){
      console.info(datas)
      if (datas !== null && datas !== undefined && datas !== [] && datas.length > 0) {
        const res = await saveExcel(datas);
        callback();
        if (res.resultCode === 200) {
          this.visibleImportFlag = false
        }
        this.fetchParams = { ...this.fetchParams };
      } else {
        this.$notify.error({ title: '提示信息', message: '没有数据可以导入' || '操作失败!' });
      }
    },
    onBeforeDownloadTemp(callback) {
      getRepairData(this.fetchParams).then(res => {
        if (res.resultCode == 200) {
          console.info(res)
          console.info('导出的数据')
          const data = res.data.records.map(i => {
            return {
              roNo: i.roNo,
              ownerCode:i.ownerCode
            }
          })
          callback(data)
        }
      })
    },
    selectData(val) {
      if(val.length>0){
        this.isOpen=false;
        this.tableData = val;
      } else {
        this.isOpen=true;
        this.tableData = [];
      }
    },
    async doComplete() {
      let str = '';
      this.tableData.map(x => {
        str += x.roId + ',';
      });
      str = str.substring(0,str.length-1)
      console.info(str)
      const res = await batchConpleteUpdate({ ids: str });
      this.fetchParams = { ...this.fetchParams };
    },
  }
}
</script>
